//
//  LBDivideColorFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 4/2/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#include "LBDivideColorFilter.h"
#include "LBGraphics.h"

char fShaderStrDivideColor[] = ""
"precision mediump float;"

"varying vec2 vtexCoor;"
"varying vec4 vposition;"
"uniform sampler2D texture;"
"uniform vec4 color;"
"uniform float opacity;"


// divide function
"vec4 divide(vec4 base, vec4 blend, float opacity){"
"   mediump float ra;"
"   if (blend.a == 0.0 || ((base.r / blend.r) > (base.a / blend.a)))"
"       ra = blend.a * base.a + blend.r * (1.0 - base.a) + base.r * (1.0 - blend.a);"
"   else"
"       ra = (base.r * blend.a * blend.a) / blend.r + blend.r * (1.0 - base.a) + base.r * (1.0 - blend.a);"


"   mediump float ga;"
"   if (blend.a == 0.0 || ((base.g / blend.g) > (base.a / blend.a)))"
"       ga = blend.a * base.a + blend.g * (1.0 - base.a) + base.g * (1.0 - blend.a);"
"   else"
"       ga = (base.g * blend.a * blend.a) / blend.g + blend.g * (1.0 - base.a) + base.g * (1.0 - blend.a);"


"   mediump float ba;"
"   if (blend.a == 0.0 || ((base.b / blend.b) > (base.a / blend.a)))"
"       ba = blend.a * base.a + blend.b * (1.0 - base.a) + base.b * (1.0 - blend.a);"
"   else"
"       ba = (base.b * blend.a * blend.a) / blend.b + blend.b * (1.0 - base.a) + base.b * (1.0 - blend.a);"

"   mediump float a = blend.a + base.a - blend.a * base.a;"

"   vec4 result = vec4(ra, ga, ba, a);"

"    result = mix(base, result, opacity);"
"    return result;"
"}"
// END divide function


"void main()"
"{"
"    lowp vec4 textureColor = texture2D(texture, vtexCoor);"
"    textureColor = divide(textureColor, color, opacity);"
"    gl_FragColor = textureColor;"
"}";

LBDivideColorFilter::LBDivideColorFilter(){
    init(0, fShaderStrDivideColor);
    LBGraphics::getInstance()->useProgram(program);
    colorUniform = program->uniformIndex("color");
    opacityUniform = program->uniformIndex("opacity");
    setColor(1.0f, 1.0f, 1.0f);
    setOpactiy(1.0f);
}